package orange.com.openstack.api;

import java.net.HttpURLConnection;

import orange.com.openstack.sahara.data.AuthenticationToken;
import orange.com.openstack.sahara.httpConnection.RestCall;

import com.jayway.jsonpath.JsonPath;

/**
 * class providing authenticaiton machanism
 * 
 * @author osvaldo.cocucci@gmail.com
 * 
 */
public class Authentications {

	String userName, tenantName, pwd, urlPath;

	/**
	 * @param urlPath
	 * @param userName
	 * @param tenantName
	 * @param pwd
	 * 
	 *            constructor for authentication
	 */
	public Authentications(String urlPath, String userName, String tenantName,
			String pwd) {
		this.userName = userName;
		this.tenantName = tenantName;
		this.pwd = pwd;
		this.urlPath = urlPath;
	}

	/**
	 * 
	 * method returning a token from keystone. This token can then be used to
	 * request on openstack or sahara edp ...
	 */
	public AuthenticationToken getAuthenticationToken() {
		RestCall caller = new RestCall();
		String payload = "{\"auth\": {\"tenantName\": \"" + tenantName
				+ "\", \"passwordCredentials\": {\"username\": \"" + userName
				+ "\", \"password\": \"" + pwd + "\"}}}";
		HttpURLConnection connection = caller.connect(urlPath, payload, "POST",
				null);
		AuthenticationToken generatedToken;
		String JSONreponse = caller.getResponse(connection);
		String issued_at = JsonPath.read(JSONreponse,
				"$.access.token.issued_at");
		String expires = JsonPath.read(JSONreponse, "$.access.token.expires");
		String token = JsonPath.read(JSONreponse, "$.access.token.id");
		String tenantId = JsonPath
				.read(JSONreponse, "$.access.token.tenant.id");
		String tenantName = JsonPath.read(JSONreponse,
				"$.access.token.tenant.name");
		generatedToken = new AuthenticationToken(issued_at, expires, tenantId,
				token, tenantName);

		connection.disconnect();
		return generatedToken;

	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getTenantName() {
		return tenantName;
	}

	public void setTenantName(String tenantName) {
		this.tenantName = tenantName;
	}

	public String getPwd() {
		return pwd;
	}

	public void setPwd(String pwd) {
		this.pwd = pwd;
	}

	public String getUrlPath() {
		return urlPath;
	}

	public void setUrlPath(String urlPath) {
		this.urlPath = urlPath;
	}
}
